<?php
	if(!isset($_SESSION['PHPSESSID'])){
		session_start();
	}
	header("Content-Type: application/x-www-form-urlencoded; charset=utf-8");

	require_once 'HTTP/Request2.php';

########## ##########  START GLOBAL config ########## ##########	
$OFFLINE = false;
$trace = false;
$xmlfile = 'genericframe.xml'; // used by offline mode - no SQL to genericframe DB is called
########## ##########  END GLOBAL config  ########## ##########
$template = '';
$applicationName = '';
$action = '';
$startpage = '';
$traceStr = '';


	$headers = getallheaders();
	$map = $_REQUEST;
	$sid = 	$map['PHPSESSID'];
	unset($map['PHPSESSID']);	// done on purphose
		
########## ##########  START THE TRACE  ########## ##########
ob_start();	
########## ##########  WRITE THE HEADERS & REQUEST  ########## ##########
print_r($headers);
########## ##########  START PROCESSING  ########## ##########
	{	
		foreach ( $map as $key => $val) {
			$map[$key] = str_replace("\\", '', $val);
		}

		print_r($map);
		$applicationName = $map['applicationName'];
		$action = $map['action'];		
	}
	
	$OFFLINE = false;	
	if (file_exists($applicationName.".xml")) { 
		$OFFLINE = true;
		$xmlfile = $applicationName.".xml";
	}	
	
	########## ##########  OFFLINE ONLINE  ########## ##########	
	########## #####  SAME as online just read the XML   ########## ######
	if ($OFFLINE == true) {		
		$xmlinfoS = simplexml_load_file($xmlfile);
		/* Relative paths also work... */		
		$path ="//*[applicationName='".$applicationName."']";
		$xpathResult = $xmlinfoS->xpath($path);
		
		echo '***XPATH '.$path."\r\n";
		print_r($xpathResult[0]);
		$simpleXMLElement = $xpathResult[0];
		
		$appApplicationinstance_id = $simpleXMLElement->id;
		$appStartPageTypeAction = $simpleXMLElement->startPageTypeAction;
		$appStartPage = $simpleXMLElement->startPage;
		$appApplicationUri = $simpleXMLElement->applicationUri;
		$appTemplateLocation = $simpleXMLElement->templateLocation;
				
		if ($action != null && trim($action) != '') {
			$taction = str_replace("'", "''", $action); //  convert ' -> '' needed for SQL execute		

			$path ="//*[applicationInsanceId='".$appApplicationinstance_id."']";	
			$xpathActionResult = $xmlinfoS->xpath($path);

			echo "***Execute Action XPATH :".date("H:i:s   ").$path."\r\n";
			while(list( , $node) = each($xpathActionResult)) {
				if (strcmp($node->actionName,$action) == 0) {			    
					echo "***Found Action :\r\n";
					print_r($node);
					$template = $node->startPage;
					$actionUri = $node->actionUri;
					
					break;
				}
			}	
		} else {
			$template = $appStartPage;
		}
	} else {
		include_once("dbFactory.php");

		$sql = "select * from applicationinstance where applicationName = '$applicationName'";
		$applicationinstanceResult = &$conn->Execute($sql); 
		if (!$applicationinstanceResult->EOF) {
			$appApplicationinstance_id = $applicationinstanceResult->fields['id'];
			$appStartPageTypeAction = $applicationinstanceResult->fields['startPageTypeAction'];
			$appStartPage = $applicationinstanceResult->fields['startPage'];
			$appApplicationUri = $applicationinstanceResult->fields['applicationUri'];
			$appTemplateLocation = $applicationinstanceResult->fields['templateLocation'];

			if ($action != null && $action != '') {
				$taction = str_replace("'", "''", $action); //  convert ' -> '' needed for SQL execute
				
				$sqlaction = "select * from applicationaction where applicationInsanceId = $appApplicationinstance_id and actionName = '$taction'";
				$applicationactionResult = &$conn->Execute($sqlaction); 
				$applicationinstanceResult->Close(); # optional
				$conn->Close(); # optional				
				
				echo "***Execute Action SQL :".date("H:i:s   ").$sqlaction."\r\n";
				if (!$applicationactionResult->EOF) {
					$template = $applicationinstanceResult->fields['startPage'];			
					$actionUri = $applicationactionResult->fields['actionUri'];			
				} else {
					// Error report
				}
			} else {
				$template = $appStartPage;
			}
		}	
	}

	########## ##########  We now have everything what we need  ########## ##########
	$action = str_replace("\\", '', $action);		
	if (true) {			
		if (isset($map['filename'])) {
			$actionUri = $map['filename'];
		}	
		echo '***FileName:'.$actionUri."\r\n";	
		$url = parse_url($appApplicationUri.'genericframesource.php');
		$path = (!empty($url['path']) ? $url['path'] : "/").(!empty($url['query']) ? "?".$url['query'] : "");

		// call the php
		$response = "";
		echo '***Calling:'. 'http://'.$url['host'].$path;				
		$client = new HTTP_Request2('http://'.$url['host'].$path, HTTP_Request2::METHOD_POST);
		$client->addPostParameter("RequestType", $map['requesttype']);
		$client->addPostParameter("Data", $map['data']);
		$client->addPostParameter("FileName", $actionUri);
		$responseA = $client->send();
		$response = $responseA->getBody();
		$callStatus = $responseA->getStatus();
		
		$cur_encoding = mb_detect_encoding($response) ; 
		echo "***Response encoded:".$cur_encoding.'   '.date("H:i:s   ")."\r\n";
		echo "***Response status:".$callStatus.'   '.date("H:i:s   ").$path."\r\n";
		echo $response;
					
		// in the case document could not be loaded as XML for what ever reasion , send a error
		if ($status != 1 || $callStatus == '404') {
                     // $response = 'For these project view source not available.';
		}
                
	}	
	echo "*** OUTPUT SEND TO FLEX".date("H:i:s   ")."\r\n";

	########## ##########  WRITE THE TRACE  ########## ##########
	$my_php = ob_get_contents();
	ob_end_clean();
	$myFile = ".traceSource".$applicationName.".txt";
	$fh = fopen("trace/".$myFile, 'w') or die("can't open file");
	fwrite($fh, $my_php);
	fclose($fh);	
	########## ##########  OUTPUT SEND TO FLEX  ########## ##########
	########## ##########  START THE PHPINFO  ########## ##########
	if ($trace) {
		ob_start();	
		phpinfo () ;
		$pinfo = ob_get_contents () ;
		ob_end_clean () ;
		$fh = fopen("trace/trace.html", 'w') or die("can't open file");
		fwrite($fh, $pinfo);
		fclose($fh);		
	}
	########## ##########  END THE PHPINFO  ########## ##########
	
	// $output->encoding='utf-8';
	// echo $response;
        echo urldecode($response);
?>
